<template>
  <div class='container'>
    <el-card>
      <!-- 标题区域 -->
      <div slot="header" class="clearfix">
        <span>试题录入</span>
      </div>
      <!-- 表单区域 -->
      <el-form :model="questionInfo" :rules="rules" ref="Form" label-width="100px" class="demo-ruleForm">
        <el-form-item label="学科: " prop="subjectID">
          <el-select  v-model="questionInfo.subjectID" placeholder="请选择" @change="subjectSelectChangeHandle">
            <el-option v-for="item in subjetList" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="目录: ">
          <el-select placeholder="请选择" v-model="questionInfo.catalogID">
            <el-option v-for="item in directoryList" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="企业: " prop="enterpriseID">
          <el-select placeholder="请选择" v-model="questionInfo.enterpriseID">
            <el-option v-for="item in companyList" :key="item.id" :label="item.company" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="城市: " prop="province">
          <el-col :span="4">
            <el-select  v-model="questionInfo.province" @change="cityChangeHandle" placeholder="请选择">
              <el-option v-for="(item,index) in cityList" :key="index" :label="item" :value="item"></el-option>
            </el-select>
          </el-col>
          <el-col :span="4">
            <el-select  v-model="questionInfo.city" placeholder="请选择">
              <el-option v-for="(item,index) in cityAreaList" :key="index" :label="item" :value="item"></el-option>
            </el-select>
          </el-col>
        </el-form-item>
        <el-form-item label="方向: " prop="direction">
            <el-select  v-model="questionInfo.direction" placeholder="请选择">
              <el-option label="o2o" value="o2o"></el-option>
              <el-option label="外包服务" value="外包服务"></el-option>
              <el-option label="企业服务" value="企业服务"></el-option>
              <el-option label="互联网金融" value="互联网金融"></el-option>
              <el-option label="企业咨询" value="企业咨询"></el-option>
              <el-option label="互联网" value="互联网"></el-option>
              <el-option label="电子商务" value="电子商务"></el-option>
              <el-option label="其他" value="其他"></el-option>
            </el-select>
          </el-form-item>
        <el-form-item label="题型: " prop="resource">
          <el-radio-group v-model="questionInfo.questionType">
            <el-radio label="1">单选</el-radio>
            <el-radio label="2">多选</el-radio>
            <el-radio label="3">简答</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="难度: " prop="resource">
          <el-radio-group v-model="questionInfo.difficulty">
            <el-radio label="1">简单</el-radio>
            <el-radio label="2">一般</el-radio>
            <el-radio label="3">困难</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- 题干 -->
        <el-row>
          <el-col>
            <el-form-item label-width="120px" prop="question" label="题干：">
              <quill-editor class="quill-editor" ref="myTextEditor" v-model="questionInfo.question" style="height:180px;"></quill-editor>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 选项 -->

        <!-- 单选 -->
        <template v-if="questionInfo.questionType === '1'">
          <div v-for="(item, index) in optionsArr" :key="index">
            <el-row v-if="index < 4">
              <el-col>
                <el-form-item label-width="120px" label="选项：">
                  <el-row>
                    <el-col :span="1">
                      <el-radio :label="index" v-model="radio">{{ item.code }}：</el-radio>
                    </el-col>
                    <el-col :span="5"> <el-input v-model="item.title"></el-input></el-col>
                    <el-col :span="10">
                      <el-upload class="upload-demo" action="#" multiple :limit="3">
                        <el-button class="upload_btn">点击上传</el-button>
                      </el-upload>
                    </el-col>
                  </el-row>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </template>

        <!-- 多选 -->
        <template v-if="questionInfo.questionType === '2'">
          <div v-for="(item, index) in optionsArr" :key="index">
            <el-checkbox-group v-model="checkList">
              <el-row v-if="index < questionIndex">
                <el-col>
                  <el-form-item label-width="120px" label="选项：">
                    <el-row>
                      <el-col :span="1">
                        <el-checkbox :label="index">{{ item.code }}</el-checkbox>
                      </el-col>
                      <el-col :span="5"> <el-input v-model="item.title"></el-input> </el-col>
                      <el-col :span="10">
                        <el-upload class="upload-demo" action="#" multiple :limit="3">
                          <el-button class="upload_btn">点击上传</el-button>
                        </el-upload>
                      </el-col>
                    </el-row>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-checkbox-group>
          </div>
          <el-row>
            <el-col :offset="2">
              <el-button class="add_btn" type="danger" size="small" @click="addItem" style="margin-bottom: 10px">+增加选项与答案</el-button>
            </el-col>
          </el-row>
        </template>

         <!-- 解析视频 -->
        <el-row>
          <el-col :span="8">
            <el-form-item label-width="120px" label="解析视频：" prop="videoURL">
              <el-input v-model="questionInfo.videoURL"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="答案解析: " prop="answer">
          <quill-editor class="quill-editor" ref="myTextEditor" v-model="questionInfo.answer" style="height:180px">
          </quill-editor>
        </el-form-item>
        <el-form-item label="题目备注">
          <el-input type="textarea" :rows="4" placeholder="请输入内容" v-model="questionInfo.remarks">
          </el-input>
        </el-form-item>
        <el-col :span="8">
          <el-form-item label="试题标签" prop="tags" label-width="120px">
            <el-select v-model="questionInfo.tags" multiple allow-create placeholder="请选择" style="width:100%;">
              <el-option v-for="item in tagList" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :offset="18">
          <el-form-item>
            <el-button type="primary"  @click="onClick($event)">{{ $route.query.id ? '确认修改' : ' 确认提交' }}</el-button>
          </el-form-item>
        </el-col>
      </el-form>
    </el-card>
    </div>
</template>

<script>
// 富文本编辑器
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { quillEditor } from 'vue-quill-editor'

import { simple as subjectList } from '@/api/hmmm/subjects'
import { simple as directoryList } from '@/api/hmmm/directorys'
import { simple as tagList } from '@/api/hmmm/tags'
import { provinces, citys } from '@/api/hmmm/citys'
import { add, detail, update } from '@/api/hmmm/questions'
// 企业接口
import { list as companyList } from '../../api/hmmm/companys'
// 导入一个对象
import { array } from '@/api/hmmm/constants'
export default {
  data () {
    return {
      questionInfo: {
        subjectID: '', // 学科
        catalogID: null, // 目录
        enterpriseID: '', // 企业
        province: '', // 企业所在地省份
        city: '', // 企业所在城市
        direction: '', //  方向
        questionType: '1', // 题型
        difficulty: '1', // 难度
        question: '', // 题干
        // 选项
        options: [],
        videoURL: ' ', // 解析视频
        answer: '', // 答案解析
        remarks: '', // 题目备注
        tags: [''] // 试题标签
      },
      editInfo: {},
      rules: {
        subjectID: [{ required: true, message: '请选择学科!', trigger: 'blur' }],
        enterpriseID: [{ required: true, message: '请选择企业!', trigger: 'blur' }],
        province: [{ required: true, message: '请选择地区!', trigger: 'blur' }],
        direction: [{ required: true, message: '请选择方向!', trigger: 'blur' }],
        question: [{ required: true, message: '请输入题干!', trigger: 'blur' }],
        answer: [{ required: true, message: '请输入答案解析!', trigger: 'blur' }],
        videoURL: [{ required: true, message: '请输入解析视频地址!', trigger: 'blur' }],
        tags: [{ required: true, message: '请输入解析视频地址!', trigger: 'blur' }]
      },
      // 复选框列表
      checkList: [],
      // 选项的index
      questionIndex: 4,
      // 单选
      radio: '',
      // 存储选项的数组
      optionsArr: array,
      // 二级目录列表
      directory: [],
      questionInfoList: [],
      subjetList: [],
      directoryList: [],
      tagList: [],
      companyList: [],
      cityList: provinces(),
      cityAreaList: []
    }
  },
  created () {
    this.getSubjectList()
    this.getCompanyList()
    this.getQuestionInfo()
  },
  beforeUpdata () {},
  watch: {
    '$route.query.id' () {
      ++this.key
      this.$router.go(0)
      this.getQuestionsInfo()
    }
  },
  methods: {
    // 点击确认按钮
    onClick (e) {
      this.$refs.Form.validate(async valid => {
        if (!valid) {
          return false
        } else {
          switch (e.target.innerText) {
            case '确认提交' :
              this.onSubmit()
              this.$message.success('添加成功!')
              break

            case '确认修改' :
              if (this.questionInfo.tags.length > 1) {
                this.questionInfo.tags = this.questionInfo.tags.join(',')
              } else {
                this.questionInfo.tags = this.questionInfo.tags.toString()
              }
              // 试题选项操作 处理数据
              if (this.questionInfo.questionType === '1') {
                // 单选
                const Arr = this.optionsArr.slice(0, 4)
                // 判断默认勾选
                Arr.forEach((item, index) => {
                  if (index === this.radio) {
                    item.isRight = true
                  } else {
                    item.isRight = false
                  }
                })
                this.questionInfo.options = Arr
              } else if (this.questionInfo.questionType === '2') {
                const arr = this.optionsArr.slice(0, this.questionIndex)
                // 判断默认勾选
                for (let i = 0; i < arr.length; i++) {
                  this.checkList.forEach(item => {
                    if (i === item) {
                      arr[i].isRight = true
                    }
                  })
                }
                this.questionInfo.options = arr
              }
              update(this.questionInfo)
                .then(res => {
                  this.$message.success('修改成功!')
                })
              break
          }
          this.$router.push('list')
        }
      })
    },
    // 点击编辑之后获取题目的详情
    async getQuestionInfo () {
      if (this.$route.query.id) {
        const { data: res } = await detail({ id: this.$route.query.id })
        // 数据替换
        // 根据传递数据 渲染目录与tags
        directoryList({ subjectID: res.subjectID })
          .then(res => {
            this.directoryList = res.data
          })
          .catch(err => { console.log(err) })
        // tags
        tagList({ subjectID: res.subjectID })
          .then(res => {
            if (res.items.length) {
              this.tagList = res.items
            } else {
              this.tagList = []
            }
          })
          .catch(err => {
            console.log(err)
          })
        this.questionInfo = res
        if (this.questionInfo.tags.length === 0 && this.questionInfo.tags.indexOf(',') === -1) {
          this.questionInfo.tags = []
        } else if (this.questionInfo.tags.indexOf(',') === -1) {
          this.questionInfo.tags = [this.questionInfo.tags]
        } else {
          this.questionInfo.tags = this.questionInfo.tags.split(',')
        }
        this.questionIndex = this.questionInfo.options.length
        // 重新加载添加按钮所需的容器
        console.log(this.questionInfo)
        const array1 = array
        const newArr = array1.splice(+this.questionInfo.options.length)
        this.optionsArr = this.questionInfo.options.concat(newArr)
        // 重新获取目录列表并渲染

        switch (this.questionInfo.questionType) {
          // 单选
          case '1':
            this.questionInfo.options.forEach((item, index) => {
              if (item.isRight === 1) {
                this.radio = index
              }
            })
            break
            // 多选
          case '2':
            this.questionInfo.options.forEach((item, index) => {
              if (item.isRight === 1) {
                this.checkList.push(index)
              }
            })
            break
        }
      }
    },
    // 获取学科列表的函数
    getSubjectList () {
      subjectList()
        .then(res => {
          this.subjetList = res.data
        })
        .catch(err => { console.log(err) })
    },
    // 学科列表切换时获取 二级目录&标签 的函数
    subjectSelectChangeHandle () {
      this.questionInfo.catalogID = null
      this.questionInfo.tags = null
      directoryList({ subjectID: this.questionInfo.subjectID })
        .then(res => {
          this.directoryList = res.data
        })
        .catch(err => { console.log(err) })
      tagList({ subjectID: this.questionInfo.subjectID })
        .then(res => {
          if (res.data.length) {
            this.tagList = res.data
          } else {
            this.tagList = []
          }
        })
        .catch(err => {
          console.log(err)
        })
    },
    // 城市改变时的处理函数
    cityChangeHandle () {
      this.cityAreaList = citys(this.questionInfo.province)
    },
    // 获取公司的列表
    async getCompanyList () {
      const { data: res } = await companyList({
        page: 1,
        pagesize: 99
      })
      this.companyList = res.items
    },
    // 添加选项
    addItem () {
      if (this.questionIndex > 25) {
        return
      }
      this.questionIndex++
    },
    async onSubmit () {
      if (this.questionInfo.tags.length > 1) {
        this.questionInfo.tags = this.questionInfo.tags.join(',')
      } else {
        this.questionInfo.tags = this.questionInfo.tags.toString()
      }
      // 试题选项操作 处理数据
      if (this.questionInfo.questionType === '1') {
        // 单选
        const Arr = this.optionsArr.slice(0, 4)
        console.log(Arr)
        console.log(this.radio)
        // 判断默认勾选
        Arr.forEach((item, index) => {
          if (index === this.radio) {
            item.isRight = true
          } else {
            item.isRight = false
          }
        })
        this.questionInfo.options = Arr
      } else if (this.questionInfo.questionType === '2') {
        const arr = this.optionsArr.slice(0, this.questionIndex)
        // 判断默认勾选
        for (let i = 0; i < arr.length; i++) {
          this.checkList.forEach(item => {
            if (i === item) {
              arr[i].isRight = true
            }
          })
        }
        this.questionInfo.options = arr
      }
      const { data: res } = await add(this.questionInfo)
      console.log(res)
    }
  },
  components: {
    quillEditor
  }
}
</script>

<style scoped lang='scss'>
.quill-editor {
    margin-bottom: 70px;
}
</style>
